#!/bin/bash

#
# clusterDataMove.sh
# created by youngeryoyo
# of qloudgen to support table data redistribution
# 

if [ $# != 4 ];then
  echo "Usage: clusterDataMove.sh configFile [add | delete ] datanodename1,datanodename2,... database"
  exit 1;
fi
configFile=$1
operaType=$2
nodes=$3
database=$4

if [ "$operaType" != "add" ] && [ "$operaType" != "delete" ];then
  echo "add or delete only!"
  exit 2;
fi

# load configFile variables
if [ -f $configFile ]; then
  source $configFile
else
  echo "$configFile does not exist!"
  exit 3;
fi

# get an available coord server
for ((i=0; i<${#coordMasterServers[@]}; i++));do
  if [ "${coordMasterServers[$i]}" != "none" ] && [ "${coordMasterServers[$i]}" != "N/A" ]; then
      primaryCoord=${coordMasterServers[$i]}
      primaryPort=${coordPorts[$i]}
      break
  fi
done

# alter table add/remove node for all tables in $database
for table in `psql -h $primaryCoord -p $primaryPort -c "select e.nspname||'.'||a.relname from pg_class a, pgxc_class b , pg_attribute c,  pg_namespace e where a.oid = b.pcrelid and c.attnum>0 and c.attrelid = a.oid and e.oid = a.relnamespace and c.attnum = b.pcattnum"  $database`
do

   if [ `expr match "$table" ".*\."` -ne 0 ];then

       command="alter table $table $operaType node ($nodes)"
       echo psql -h $primaryCoord -p $primaryPort -c \"$command\" $database 
       psql -h $primaryCoord -p $primaryPort -c "$command" $database 

   fi

done
